layui.use(['layer', 'form', 'table', 'util', 'admin'], function () {
    var $ = layui.jquery;
    var layer = layui.layer;
    var form = layui.form;
    var table = layui.table;
    var util = layui.util;
    var admin = layui.admin;


    //渲染表格
    var genTableIns = table.render({
        elem: '#genTable',
        url: prefix + '/list',
        initSort: {
            field: 'gmtCreate'
            , type: 'desc'
        },
        where: {
            fieldName: 'gmtCreate',
            sortType: 'desc'
        },
        toolbar: ['<p>',
            '<button lay-event="importTable" class="layui-btn layui-btn-sm layui-bg-cyan icon-btn ' + listFlag + '"><i class="layui-icon layui-icon-add-1"></i>导入</button>',
            '<button lay-event="del" class="layui-btn layui-btn-sm layui-btn-danger icon-btn ' + removeFlag + '"><i class="layui-icon layui-icon-delete"></i>删除</button>',
            '</p>'].join(''),
        cols: [
            [
                {type: 'numbers', title: "序号", width: 80},
                {field: 'tableName', title: '表名称', align: 'center', sort: true},
                {field: 'tableComment', title: '表描述', align: 'center', sort: true},
                {field: 'className', title: '实体类名称', align: 'center', sort: true},
                {
                    field: 'gmtCreate', title: '创建时间', align: 'center', sort: true, templet: function (d) {
                        return dateDisplay(util, d.gmtCreate);
                    }
                },
                {
                    field: 'gmtModified', title: '更新时间', align: 'center', sort: true, templet: function (d) {
                        return dateDisplay(util, d.gmtModified);
                    }
                },
                {title: '操作', toolbar: '#genTbBar', align: 'center', minWidth: 400}
            ]
        ]
    });

    //表格搜索
    form.on('submit(genTbSearch)', function (data) {
        genTableIns.reload({where: data.field, page: {curr: 1}});
        return false;
    });

    //表格工具条点击事件
    table.on('tool(genTable)', function (obj) {
        var data = obj.data;
        if (obj.event === 'del') {
            deleteTable([data.tableId]);
        } else if (obj.event === 'sync') {
            sync(data.tableName);
        } else if (obj.event === 'preview') {
            previewCode(data);
        } else if (obj.event === 'gen') {
            genCode(data);
        }
    });

    //表头工具栏点击事件
    table.on('toolbar(genTable)', function (obj) {
        var data = table.checkStatus('genTable').data;
        if (obj.event === "importTable") {
            importTable();
        } else if (obj.event === "del") {
            data = data.map(function (item) {
                return item.tableId;
            });
            deleteTable(data);
        }
    });

    //触发排序事件
    table.on('sort(genTable)', function (obj) {
        genTableIns.reload({
            initSort: obj
            , where: {
                fieldName: obj.field
                , sortType: obj.type
            }
        });
    });

    // 导入表结构
    function importTable() {
        var importTableUrl = prefix + "/importTable";
        var height = $(window).height() - 200;
        layer.open({
            type: 2,
            area: ['840px', height + 'px'],
            offset: 'auto',
            fix: false,
            maxmin: true,
            shade: 0.3,
            title: "导入表",
            content: importTableUrl,
            btn: ['确定', '关闭'],
            // 弹层外区域关闭
            shadeClose: true,
            yes: function (index, layero) {
                // var body = layer.getChildFrame('body', index);
                var iframeWin = window[layero.find('iframe')[0]['name']];
                admin.req(prefix + "/importTable", {
                    tables: iframeWin.tableImportSelect
                }, function (resp) {
                    himio.notice.resp(resp, function () {
                        genTableIns.reload({page: {curr: 1}});
                    });
                    layer.close(index);
                }, "post");
            },
            cancel: function (index) {
                layer.close(index);
                return true;
            }
        });
    }

    //表格顶部工具栏删除
    function deleteTable(data) {
        if (data.length === 0) {
            himio.notice.warn('请选择要删除的库表数据');
            return;
        }
        admin.confirm("确认要删除选中的" + data.length + "条数据吗?", function (index) {
            admin.req(prefix + "/remove", {
                ids: data.join(",")
            }, function (resp) {
                himio.notice.resp(resp, function () {
                    genTableIns.reload({where: data.field, page: {curr: 1}});
                });
                layer.close(index);
            }, "post");
        });
    }

    //同步表结构
    function sync(tableName) {
        admin.req(prefix + "/syncDb/" + tableName, function (resp) {
            himio.notice.resp(resp);
            return false;
        });
    }

    //预览
    function previewCode(data) {
        admin.req(prefix + "/preview/" + data.tableId, function (resp) {
            himio.notice.resp(resp, function () {
                var tabContent = [];
                var respData = resp.data;
                for (var prop in respData) {
                    tabContent.push({
                        title: prop,
                        content: '<div class="code-sample" style="padding: 20px;font-family: Consolas,sans-serif;font-size: 14px;background: #fafafa;"><pre>' + respData[prop] + '</pre></div>'
                    });
                }
                layer.tab({
                    offset: '10px',
                    area: ['85%', ($(window).height() - 100) + 'px'],
                    maxmin: true,
                    tab: tabContent,
                    success: function () {
                        // first, find all the div.code blocks
                        document.querySelectorAll('div.code-sample>pre').forEach(function (el) {
                            // then highlight each
                            hljs.highlightElement(el);
                        });
                    }
                });
            }, true);
        }, 'get');

    }

    //生成代码到项目中
    function genCode(data) {
        admin.req(prefix + "/genCode/" + data.tableName, function (resp) {
            himio.notice.resp(resp);
        }, 'get');
    }

});